# Copyright (C) 2007 "dbsolution sas" 
#
# This file is part of Weebotee.
#
# Weebotee is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Weebotee is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Weebotee.  If not, see <http://www.gnu.org/licenses/>.

from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
from django.template import RequestContext

from apps.core.models.section import Section
from apps.core.models.element import Element
from libs.plug_core import *
from urllib import urlencode


def index(request, section=None ):
    try:
        section = Section.objects.getSection(request.user, section)
        if not section:
            return HttpResponseRedirect("/admin/")
        template = get_view(section)
        
        selected_articles = Element.objects.getForSection(request.user,section)
        
        default_context = {
            'section':section,
            'content':selected_articles,
            'request':request,
            'post':request.POST,
        }
        return render_to_response(
            template, default_context, context_instance=RequestContext(request)
        )
    except:
        try:
            import traceback
            e = traceback.format_exc()
            print "error! ->", e
            #from libs.dispatchers.dispatchers import traceError
            #traceError(origin="index view in frontend/views/index.py", error=e)
        except Exception, e:
            print "->", e
    return HttpResponseRedirect("/admin/")


def wizard(request, param=None):
    #use param to get the right wizard
    if not "wiz" in request.session.keys():
        #keep right wizard based on param
        request.session["wiz"] = [{"url":"registration", "login":"jump"},
                                  {"url":"billing/add", "login":"yes"},
                                  {"url":"element/add/witch:Booking/219", "login":"yes"}]
                                                                    
    else:
        request.session.modified = True
        if not request.POST and not request.GET:
            del request.session["wiz"][0]
        
    import django.core.urlresolvers as urlresolvers
    try:
        print "\033[01;32m%s\033[02;37m"%request.user
        if request.session["wiz"][0]["login"] == "yes" and not request.user.is_authenticated():
            a = urlresolvers.resolve('/login/')
            r = a[0](request, **a[2])
            if request.user.is_authenticated():
                request.session["wiz"].insert(0, request.session["wiz"][0])
                return HttpResponseRedirect("/wizard/")
        elif request.session["wiz"][0]["login"] == "jump" and request.user.is_authenticated():
            return HttpResponseRedirect("/wizard/")
        else:
            a = urlresolvers.resolve('/'+request.session["wiz"][0]["url"]+'/')
            r = a[0](request, **a[2])
        print "\033[01;38m%s\033[02;37m"%request.session["wiz"]
        try:
            if isinstance(r,HttpResponseRedirect):
                print "dah"
                request.session.modified= True
                #    del request.session["wiz"][0]
                return HttpResponseRedirect("/wizard/")
            else:
                #print r.__dict__
                return r
        except:
            return r
    except Exception, e:
        print e
        del request.session["wiz"]
        #return HttpResponseRedirect("/wizard/")
        
    
    return HttpResponseRedirect("/wizardcomplete/") # here return well done page
    
def wizardundo(request):
    try:
        del request.session['wiz']
    except:
        pass
    return HttpResponseRedirect("/")

def showElement(request, elementid):
    try:
        el = Element.objects.getElement(request.user, elementid)
        section = Section.objects.get(id=el.section_id)
    except Exception, e:
        raise Http404('Element not found')
    
    template = get_view_for_elem(el)
    default_context = {
        'section': section,
        'content':el,
        'user':request.user,
    }
    return render_to_response(template, default_context)

def addElement(request, type, parameters=""):
    # controllo wizard
    isWizard = False
    if not "wiz" in request.session.keys():
        isWizard = True
    
    try:
        section = Section.objects.get(slug__iexact='home')
    except Exception, e:
        raise Http404('Element not found')

    slug = elem_relative_section(type)
    initial_data = {
            'owner':request.user.id,
            'section': Section.objects.get(slug__exact=slug).id,
            'initialp': parameters
    }
    
    if request.POST:
        posted_data = request.POST.copy()
        form = get_form_for_etype(type)(posted_data,initial=initial_data)
        if form.is_valid():
            res = form.save()
            if request.POST.get("redirect"):
                p = request.POST.copy()
                del p["redirect"]
                del p["submit"]
                p.update({"parameters":parameters, "res":res})
                return HttpResponseRedirect(request.POST.get("redirect")+"?"+urlencode(p))
            else:
                return HttpResponseRedirect("/%s/" % elem_relative_section(type))
    else:
        form = get_form_for_etype(type)(initial=initial_data)

    m = get_model_from_etype(type)
    if hasattr(m, "Witch"):
        s = Section.objects.get(viewtype="witch:Offer")
        t = get_view(s)

        default_context = {
            'section':s,
            #'content':selected_articles,
            'request':request,
            #'user':request.user,
            'post':request.POST,
            'etype':type,
            'isWizard':isWizard
        }
        return render_to_response(t, default_context, context_instance=RequestContext(request))

    else:
        template = get_input_for_elem(type)
        default_context = { 'type':type, 'section':section, 'user':request.user, 'form':form, 'isWizard':isWizard }
        return render_to_response(template, default_context, context_instance=RequestContext(request))
